import React, { useEffect, useState, useRef } from 'react'
import type { MusicItem } from '../types'
import classNames from 'classnames'

interface Props {
  power: boolean
  list: MusicItem[]
  changeMusic: (music: MusicItem) => void
}

const Keyboard: React.FC<Props> = ({ list, power, changeMusic }) => {
  const [curId, setId] = useState<string | null>(null)
  const listRef = useRef<{
    list: MusicItem[]
    changeMusic: (music: MusicItem) => void
  }>({
    list,
    changeMusic
  })


  useEffect(() => {
    listRef.current = {
      list,
      changeMusic
    }
  }, [list, changeMusic])

  useEffect(() => {
    const mouseup = () => setId(null)
    document.addEventListener('mouseup', mouseup)
    document.addEventListener('keyup', mouseup)
    const keydown = (e: any) => {
      const music = listRef.current.list.find((item) => item.keyCode === e.keyCode)
      if (music) {
        listRef.current.changeMusic(music)
        setId(music.id)
      }
    }
    document.addEventListener('keydown', keydown)

    return () => {
      document.removeEventListener('mouseup', mouseup)
      document.removeEventListener('keyup', mouseup)
      document.removeEventListener('keydown', keydown)
    }
  }, [])

  return (
    <div className="keyboard">
      {list.map((item) => 
        <div
          key={item.id}
          className={classNames('keyboardItem', { down: curId === item.id, on: curId === item.id && power })}
          onMouseDown={() => {
            changeMusic(item)
            setId(item.id)
          }}
        >{item.keyTrigger}</div>
      )}
    </div>
  )
}

export default Keyboard